#!/bin/bash
{
	#////////////////////////////////////
	# DietPi Bug Report Script
	#
	#////////////////////////////////////
	# Created by Daniel Knight / daniel.knight@dietpi.com / dietpi.com
	#
	#////////////////////////////////////
	#
	# Info:
	# - Location: /boot/dietpi/dietpi-bugreport
	# - Called from G_EXEC
	# - Generates $G_HW_UUID.7z and uploads to dietpi.com
	readonly USAGE='
Usage: dietpi-bugreport <command>
Available commands:
  0, <empty>	Interactive menu to send or remove bug reports and review upload content
  1		Non-interactively send a bug report
 -1		Non-interactively remove an already uploaded bug report
'	#////////////////////////////////////

	# Import DietPi-Globals --------------------------------------------------------------
	. /boot/dietpi/func/dietpi-globals
	readonly G_PROGRAM_NAME='DietPi-Bugreport'
	G_CHECK_ROOT_USER
	G_CHECK_ROOTFS_RW
	G_INIT
	# Import DietPi-Globals --------------------------------------------------------------

	disable_error=1 G_CHECK_VALIDINT "$1" && INPUT=$1 || INPUT=0

	readonly SFTP_ADDR='ssh.dietpi.com:22'
	readonly SFTP_USER='dietpi-survey'
	readonly SFTP_PASS='upload2dietpi'
	readonly UPLOAD_FILENAME="$G_HW_UUID.7z"
	readonly UPLOAD_FILESIZE_LIMIT=20000000 # bytes

	# List of commands we want to run and redirect to upload archive
	readonly aCOMMAND_LIST=(

		'dpkg -l'
		'ip l'
		'ip a'
		'ip r'
		'lsusb'
		'cat /proc/cpuinfo'
		'free -m'
		'ps aux'
		'blkid'
		'mount'
		'df -Th'
		'ls /etc/rc*.d/'
		'cut -d: -f1 /etc/passwd'
		'locale'
		'ls -lAh /mnt' # dietpi_userdata location
		'dmesg'
		'uname -a'
		'lsmod'
		'aplay -l'
		'aplay -L'
		'systemctl -l status *.service'
		'systemctl -l status *.mount'
		'/boot/dietpi/dietpi-services status'

	)

	# List of files and folders we want to add to upload archive
	readonly aFILE_LIST=(

		# aCOMMAND_LIST output file
		'CMD_OUT.txt'

		# Git error file
		'G_EXEC_ERROR_REPORT'

		# Logs
		'/var/log'

		# Boot/kernel configs
		'/boot/config.txt' # RPi
		'/boot/cmdline.txt' # RPi
		'/boot/boot.ini' # Odroids
		'/boot/uenv.txt' # Sparky SBC
		'/boot/uEnv.txt' # ROCK Pi S
		'/boot/armbianEnv.txt' # Armbian
		'/boot/boot.cmd' # Armbian

		# DietPi files
		'/boot/dietpi.txt'
		'/boot/dietpi'
		'/var/lib/dietpi'
		'/var/tmp/dietpi'
		'/run/dietpi'

		# Login scripts
		# - bash shell
		'/etc/bash.bashrc'
		'/etc/bashrc.d'
		'/root/.bashrc'
		# - login shell
		'/etc/profile'
		'/etc/profile.d'
		'/root/.profile'

		# System
		'/etc/rc.local'
		'/etc/X11/xorg.conf'
		'/etc/X11/xorg.conf.d'
		'/etc/asound.conf'
		'/etc/network/interfaces'
		'/etc/network/interfaces.d'
		'/etc/wpa_supplicant/wpa_supplicant.conf'
		'/etc/fstab'
		'/etc/sysctl.conf'
		'/etc/sysctl.d'

		# Services
		'/etc/init.d'
		'/etc/systemd/system'
		'/lib/systemd/system'
		'/usr/local/lib/systemd/system'

		# APT
		'/etc/apt/sources.list'
		'/etc/apt/sources.list.d'
		'/etc/apt/preferences'
		'/etc/apt/preferences.d'
		'/etc/apt/apt.conf.d'

	)

	Generate_Upload_File(){

		# Generate command output file
		for i in "${aCOMMAND_LIST[@]}"
		do

			echo -e "\n----------\n$i\n----------" >> CMD_OUT.txt
			$i &>> CMD_OUT.txt

		done

		# Have the Git error in 1st directory
		[[ -f '/tmp/G_EXEC_ERROR_REPORT' ]] && G_EXEC cp /tmp/G_EXEC_ERROR_REPORT G_EXEC_ERROR_REPORT

		# Allow warnings (exit code 1), e.g. when files are missing or could not be compressed (but have been added to archive)
		G_EXEC_POST_FUNC(){ [[ $exit_code == 1 ]] && exit_code=0; }

		G_EXEC_DESC='Packing upload archive' G_EXEC 7zr a -m0=lzma2 -mx=9 -spf "$UPLOAD_FILENAME" "${aFILE_LIST[@]}"

		# Exit if size of upload archive exceeds limit
		(( $(stat -c '%s' "$UPLOAD_FILENAME") > $UPLOAD_FILESIZE_LIMIT )) || return 0

		G_DIETPI-NOTIFY 1 'The bug report upload archive appears to be unexpected large. Please inspect and in case clean up the locations to be uploaded, as their size should never be that large:'
		printf "%s\n" "${aFILE_LIST[@]}"
		exit 1

	}

	Upload_Bug_Report(){

		[[ $INPUT == 1 ]] && G_EXEC_DESC='Sending bug report' || G_EXEC_DESC='Purging bug report'

		G_EXEC curl --connect-timeout 8 --retry 1 --retry-delay 4 -sSvT "$UPLOAD_FILENAME" "sftp://$SFTP_USER:$SFTP_PASS@$SFTP_ADDR/bugreport/"

		[[ $INPUT == 1 ]] && G_DIETPI-NOTIFY 2 "Reference code: \e[33m$G_HW_UUID"

	}

	#/////////////////////////////////////////////////////////////////////////////////////
	# Main Loop
	#/////////////////////////////////////////////////////////////////////////////////////
	# Interactive menu
	while (( $INPUT == 0 ))
	do

		G_WHIP_MENU_ARRAY=(

			'1' ': Send bug report archive to help the developers investigate an issue.'
			'2' ': Remove my previously uploaded bug report.'
			'3' ': Show me what is included with the upload archive.'

		)

		G_WHIP_MENU 'By sending a bug report file, you can help the developers to investigate your issue, in relation to your report on GitHub or the DietPi forum.
The file is sent via secured connection to our SFTP server and is stored there unreadable to the public upload user.
The file will be removed after your issue is solved and you can remove it by yourself as well by running "dietpi-bugreport -1" or via this menu.\n
Would you like to send a bug report archive or remove an already uploaded one?' || exit 0

		if (( $G_WHIP_RETURNED_VALUE == 1 )); then

			INPUT=1

		elif (( $G_WHIP_RETURNED_VALUE == 2 )); then

			INPUT=-1

		elif (( $G_WHIP_RETURNED_VALUE == 3 )); then

			G_WHIP_MSG "The upload will contain the following command outputs:
\n$(printf "\t- %s\n" "${aCOMMAND_LIST[@]}")
\nIt will contain as well the following files and directories:
\n$(printf "\t- %s\n" "${aFILE_LIST[@]}")"

		fi

	done

	if [[ $INPUT == 1 ]]; then

		# Generate 7z bug report file
		Generate_Upload_File

	elif [[ $INPUT == -1 ]]; then

		# Send empty file to clear already uploaded bug report
		> "$UPLOAD_FILENAME"

	else

		G_DIETPI-NOTIFY 1 "Invalid input command ($INPUT). Aborting...\n$USAGE"
		exit 1

	fi

	# Upload bug report file
	Upload_Bug_Report

	#-----------------------------------------------------------------------------------
	exit 0
	#-----------------------------------------------------------------------------------
}
